
import 'package:flutter/material.dart';
import 'package:flutter_structure/utils/logger.dart';

class Monitor {
  final Map<String, int> _timestamps = {};
  int _frameCount = 0; 
  int _lastFrameTime = DateTime.now().millisecondsSinceEpoch;


  void mark(String stage) {
    final now = DateTime.now().millisecondsSinceEpoch;
    _timestamps[stage] = now;
    Logger.info("Marked stage: $stage at $now", tag: "PerformanceMonitor");
  }


  int duration(String startStage, String endStage) {
    if (_timestamps.containsKey(startStage) && _timestamps.containsKey(endStage)) {
      final duration = _timestamps[endStage]! - _timestamps[startStage]!;
      Logger.debug(
        "Duration from $startStage to $endStage: ${duration}ms",
        tag: "PerformanceMonitor",
      );
      return duration;
    }
    Logger.warn(
      "Cannot calculate duration, one or both stages are missing: $startStage, $endStage",
      tag: "PerformanceMonitor",
    );
    return -1; 
  }


  void logStartupTimes() {
    Logger.info("Startup Monitor Results:", tag: "PerformanceMonitor");
    final stages = _timestamps.keys.toList();
    for (int i = 1; i < stages.length; i++) {
      duration(stages[i - 1], stages[i]);
    }
    if (stages.length > 1) {
      final totalDuration = duration(stages.first, stages.last);
      Logger.info("Total Startup Time: ${totalDuration}ms", tag: "PerformanceMonitor");
    }
  }


  void startFPSMonitoring() {
    WidgetsBinding.instance.addPostFrameCallback((_){
      mark("firstFrameRenderd");
      logStartupTimes();
      WidgetsBinding.instance.addPostFrameCallback(_frameCallback); // 启动帧率监控
    });
  }

  void _frameCallback(Duration timestamp) {
    _frameCount++;
    final now = DateTime.now().millisecondsSinceEpoch;

    // 每秒计算并打印帧率
    if (now - _lastFrameTime >= 1000) {
      Logger.warn("Current FPS: $_frameCount", tag: "FPSMonitor");
      // 如果 FPS 低于 60，打印警告
      if (_frameCount < 60) {
        Logger.error("Low FPS detected: $_frameCount", tag: "FPSMonitor" );
      }
      _frameCount = 0;
      _lastFrameTime = now;
    }

    // 持续监听下一帧
    WidgetsBinding.instance.addPostFrameCallback(_frameCallback);
  }

  void stopFPSMonitoring() {
    Logger.info("FPS monitoring stopped.", tag: "FPSMonitor");
    // 停止监听帧的逻辑，可以用变量控制后续行为
  }
}